package main

import (
	"fmt"
	"github.com/gccai/write_helper/config"
	"github.com/gccai/write_helper/handler"
	"github.com/gccai/write_helper/model"
	"github.com/gccai/write_helper/repository"
	"github.com/gccai/write_helper/service"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	"log"
)

var (
	DB             *gorm.DB
	UserHandler    handler.UserHandler
	BookHandler    handler.BookHandler
	ChapterHandler handler.ChapterHandler
	DesignHandler  handler.DesignHandler
)

func initViper() {
	if err := config.Init(""); err != nil {
		panic(err)
	}
}

func initDB() {
	fmt.Println("数据库 init...")
	var err error
	conf := &model.DBConf{
		Host:     viper.GetString("database.host"),
		User:     viper.GetString("database.username"),
		Password: viper.GetString("database.password"),
		DbName:   viper.GetString("database.name"),
	}
	c := fmt.Sprintf("%s:%s@tcp(%s)/%s?parseTime=true&charset=utf8mb4&parseTime=%t&loc=%s",
		conf.User,
		conf.Password,
		conf.Host,
		conf.DbName,
		true,
		"Local")
	DB, err = gorm.Open("mysql", c)
	if err != nil {
		log.Fatalf("connect error: %v\n", err)
	}
	DB.SingularTable(true)
	DB.AutoMigrate(&model.User{}, &model.Book{}, &model.Chapter{}, &model.Design{})
	fmt.Println("数据库 init 结束...")
}

func initHandler() {
	UserHandler = handler.UserHandler{
		UserSrv: service.UserService{
			Repo: repository.UserRepository{
				DB: DB,
			},
		},
	}
	BookHandler = handler.BookHandler{
		BookSrv: service.BookService{
			Repo: repository.BookRepository{
				DB: DB,
			},
		},
	}
	ChapterHandler = handler.ChapterHandler{
		ChapterSrc: service.ChapterService{
			Repo: repository.ChapterRepository{
				DB: DB,
			},
		},
		Booksrc: service.BookService{
			Repo: repository.BookRepository{
				DB: DB,
			},
		},
	}
	DesignHandler = handler.DesignHandler{
		DesignSrv: service.DesignService{
			Repo: repository.DesignRepository{
				DB: DB,
			},
		},
	}

}

func init() {
	initViper()
	initDB()
	initHandler()
}
